package com.cheng.spider.request;

import com.cheng.spider.exception.UnsupportedHttpMethodException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;

import java.net.URI;
import java.util.Map;

public abstract class ParameterConfigurableRequester extends HeaderConfigurableRequester {
    @Override
    public void configParameters(HttpRequestBase request) {
        fullParameters(request);
    }

    private void fullParameters(HttpRequestBase request) {
        if (request instanceof HttpGet) {
            urlEncode((HttpGet) request);
        } else if (request instanceof HttpPost) {
            formData((HttpPost) request);
        } else {
            throw new UnsupportedHttpMethodException("不支持的HTTP请求方法:" + request.getMethod());
        }
    }

    private void formData(HttpPost request) {
        //TODO
    }

    private void urlEncode(HttpGet request) {
        Map<String, Object> map = parameters();
        StringBuilder query = new StringBuilder();
        if (map != null && map.entrySet().size() != 0) {
            map.forEach((k, v) -> {
                if (v instanceof String[]) {
                    for (String item : (String[]) v) {
                        query.append("&").append(k).append("=").append(item);
                    }
                } else if (v instanceof String) {
                    query.append("&").append(k).append("=").append(v);
                } else {
                    throw new RuntimeException("不支持的URL参数类型：" + v.getClass());
                }
            });
            request.setURI(URI.create(request.getURI() + "?" + query));
        }
    }

    protected Map<String, Object> parameters() {
        return null;
    }
}
